package queenChessProblem;

import java.util.List;

import genetic_algorithm.Chromosome;
import genetic_algorithm.FitnessFunction;

/**
 * Calculates fitness of a chromosome in the genetic algorithm
 * to solve the queens problem.
 * Such chromosome's fitness is 1 / (#collisions + 1)
 */
public class QueensFitnessFunction implements FitnessFunction {

	@Override
	public double getFitness(Chromosome chromosome) {
		List<Object> queens = chromosome.getAllValues();
		double penalty = 0;
		int col1 = 0, col2 = 0;
		for (int row1 = 0; row1 < 8; ++row1) {
			for (int row2 = row1+1; row2 < 8; ++row2) {

				// do not compare the same position
				if (row1 == row2) {
					continue;
				}

				// extract columns
				col1 = (Integer) queens.get(row1);
				col2 = (Integer) queens.get(row2);
				
				// check if on same column or same diagonal
				if (col1 == col2 || Math.abs((row1 - row2)) == Math.abs((col1 - col2))) {
					++penalty;
				}
			}
		}

		return calcFitness(penalty);
	}

	private double calcFitness(double penalty) {
		return (1.0 / (penalty + 1))*100;
	}

}